<template>
  <div>
    <iframe ref="fastgptIframe" v-show="isIframeLoaded" @load="onIframeLoad" src="http://localhost:3000" width="100%"
      height="100%" />
  </div>
</template>

<script>
export default {
  name: 'FastGPT',
  data() {
    return {
      isIframeLoaded: false,
      loginAttempts: 0,
      maxLoginAttempts: 5,
      isLoggedIn: false // 新增登录状态标记
    }
  },
  mounted() {
    this.isLoggedIn = localStorage.getItem('fastgpt_logged_in') === 'true'
    window.addEventListener('message', this.handleMessage)
    this.isIframeLoaded = true
  },
  beforeUnmount() {
    // 清理事件监听，避免内存泄漏
    window.removeEventListener('message', this.handleMessage)
  },
  methods: {
    handleMessage(event) {
      localStorage.setItem('fastgpt_logged_in', 'true')
      this.isIframeLoaded = true
    },

    onIframeLoad() {
      console.log('iframe加载完成')

      // 如果已经登录，则不需要尝试登录
      if (this.isLoggedIn) {
        console.log('检测到已登录状态，跳过登录过程')
        this.isIframeLoaded = true
        return
      }

      // 未登录则开始尝试登录
      console.log('未检测到登录状态，开始尝试登录')
      this.attemptLogin()
    },

    attemptLogin() {
      // 如果已经登录，则不再尝试
      if (this.isLoggedIn) {
        this.isIframeLoaded = true
        return
      }

      // 定期尝试发送登录请求，直到收到响应或达到最大尝试次数
      if (this.loginAttempts >= this.maxLoginAttempts) {
        console.warn('达到最大登录尝试次数，请检查FastGPT是否正确配置')
        // 即使登录失败也显示iframe，让用户可以手动登录
        this.isIframeLoaded = true
        return
      }

      this.sendLoginInfo()

      // 安排下一次尝试
      this.loginAttempts++
      setTimeout(() => {
        if (!this.isIframeLoaded && !this.isLoggedIn) {
          this.attemptLogin()
        }
      }, 2000)
    },

    sendLoginInfo() {
      const iframe = this.$refs.fastgptIframe
      if (iframe && iframe.contentWindow) {
        try {
          console.log(`第${this.loginAttempts}次尝试发送登录消息`)
          iframe.contentWindow.postMessage({
            type: 'login',
            username: 'root',
            password: 'shibohengtong'
          }, '*')
        } catch (error) {
          console.error('发送消息失败:', error)
        }
      }
    }
  }
}
</script>

<style scoped>
iframe {
  width: 100%;
  height: calc(100vh - 100px);
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: calc(100vh - 100px);
  font-size: 18px;
  color: #409eff;
}
</style>
